package com.csist.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.csist.pojo.po.basicInfoModule.EducationBackground;
import com.csist.pojo.po.basicInfoModule.EducationMethod;
import com.csist.service.po.basicInfoModule.EducationMethodService;
import com.csist.service.po.basicInfoModule.impl.EducationMethodServiceImpl;
import com.csist.util.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/educationMethod")
public class EducationMethodServlet extends HttpServlet {
    private JSONObject jsonObject;
    private EducationMethodService educationMethodService = new EducationMethodServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //        这里如果request没有json字符串，则jsonObject为null（获取不到）
        jsonObject = JSONUtil.getJSONObject(request);
        if (jsonObject == null) {
            err(request, response);
            return;
        }
        String type = jsonObject.getString("type");
        if (type != null) {
            switch (type) {
                case "add":
                    add(request, response);
                    break;
                case "query":
                    show(request, response);
                    break;
                case "edit":
                    edit(request, response);
                    break;
                case "editByState":
                    editByState(request, response);
                    break;
                case "conditionalShow":
                    conditionalShow(request, response);
                    break;
                default:
                    err(request, response);
            }
        } else {
            err(request, response);
        }
    }

    private void conditionalShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        //        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;
        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");

        EducationMethod educationMethod = new EducationMethod();
        educationMethod.setEmName(group.getString("emName"));
        educationMethod.setEmCode(group.getString("emCode"));
        educationMethod.setEmState(group.getInteger("emState") == 1);
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<EducationMethod> list = educationMethodService.findEducationMethodFuzzy(educationMethod);
        if (list != null) {
            PageInfo<EducationMethod> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);


    }

    /**
     * 修改教学方式状态（逻辑删除）
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void editByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        Integer emId = group.getInteger("emId");
        int i = educationMethodService.updateEducationMethodByState(emId);
        Boolean status;
        String msg;
        if (i > 0) {
            status = true;
            msg = "修改状态成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改状态失败...";
        statusMsg(request, response, status, msg);

    }

    /**
     * 修改教学方式信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        EducationMethod educationMethod = new EducationMethod();
//        从group中获取传输过来的教学方式名称
        String emName = group.getString("emName");
//        从group中获取传输过来的教学方式代码
        String emCode = group.getString("emCode");
//        从group中获取传输过来的教学方式状态
        Integer emState = group.getInteger("emState");
        if (emName == null || emName.isEmpty() || emCode == null || emCode.length() != 1 || emState == null) {
            err(request, response);
            return;
        }

        educationMethod.setEmName(emName);
//        将教学方式代码字母转大写，这里提前处理不影响，数据库查询char字段不区分大小写
        educationMethod.setEmCode(emCode.toUpperCase());
        educationMethod.setEmState(emState == 1);
        List<EducationMethod> list = educationMethodService.findEducationMethod(educationMethod);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "查找出与修改数据有相符的，请修改成正确信息...";
            statusMsg(request, response, status, msg);
            return;
        }
        educationMethod.setEmId(group.getInteger("emId"));
        int i = educationMethodService.updateEducationMethod(educationMethod);
        if (i > 0) {
            status = true;
            msg = "修改信息成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改信息失败...";
        statusMsg(request, response, status, msg);

    }

    /**
     * 添加教学方式数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        EducationMethod educationMethod = new EducationMethod();
//        从group中获取传输过来的教学方式名称
        String emName = group.getString("emName");
//        从group中获取传输过来的教学方式代码
        String emCode = group.getString("emCode");
        if (emName == null || emName.isEmpty() || emCode == null || emCode.length() != 1) {
            err(request, response);
            return;
        }
        educationMethod.setEmName(emName);
        educationMethod.setEmCode(emCode.toUpperCase());
//        判断是否有重复的教学方式信息（根据教学方式名称和教学方式代码），有就给出提示信息并退出
        List<EducationMethod> list = educationMethodService.findEducationMethod(educationMethod);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "添加数据已存在...";
            statusMsg(request, response, status, msg);
            return;
        }
        int i = educationMethodService.addEducationMethod(educationMethod);
        if (i > 0) {
            status = true;
            msg = "添加数据成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "添加数据失败...";
        statusMsg(request, response, status, msg);
    }

    /**
     * 显示所有教学方式信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void show(HttpServletRequest request, HttpServletResponse response) throws IOException {

//        当jsonObject为空时
        if (jsonObject == null) {
            err(request, response);
            return;
        }

//        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;


        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<EducationMethod> list = educationMethodService.findAll();
        if (list != null) {
            PageInfo<EducationMethod> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        map.put("pagination", null);
        map.put("status", false);
        map.put("msg", "无匹配数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }


    private void err(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "传送了无效数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void findNoData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pagination", null);
        map.put("status", false);
        map.put("msg", "无匹配数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void statusMsg(HttpServletRequest request, HttpServletResponse response, Boolean status, String msg) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("msg", msg);
        response.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
